import React, {Component} from "react";
import router from "umi/router";
import {connect} from "dva";
import {Row, Steps, Menu, Dropdown, Icon, Modal, Button, Spin} from "antd";
// import cn from "classnames";
import {isPhone} from 'utils/comm';
import FileView from "components/FileView";
import RecordDetail from "./RecordDetail";
import FormDetail from "./FormDetail";
import SecondProcessRecord from "./SecondProcessRecord";
import styles from "./TemplateProcessRecord.less";

const {Step} = Steps;

/* const mockStep = 2;
const mockData = [
  {
    taskNodeTime: "2019-06-09 12:30",
    operator: "张三",
    tasName: "发起流程",
    approval: "通过",
    status: "正常",
    taskNodeType: "start",
    taskStatus: "已处理",
    activityId: "t_b_1596770",
  },
  {
    taskNodeTime: "2019-06-09 12:30",
    operator: "李四",
    tasName: "分局审批",
    approval: "通过",
    status: "正常",
    taskNodeType: "node",
    taskStatus: "已处理",
    activityId: "t_b_1596771",
  },
  {
    taskNodeTime: "2019-06-09 12:30",
    operator: "张三",
    tasName: "分局审批",
    approval: "通过",
    status: "正常",
    taskNodeType: "node",
    taskStatus: "待处理",
    activityId: "t_b_1596772",
  },
  {
    taskNodeTime: "2019-06-09 12:30",
    operator: ["张三", "李四", "王二", "吴一"],
    tasName: "i派出所审批",
    status: "预警",
    taskNodeType: "end",
    taskStatus: "待处理",
    activityId: "t_b_1596773",
    processInstanceId: "bd27177ddaa711e9b3be005056a0b338",
  },
]; */
const Status = {
  pass: "通过",
  reject: "驳回",
  // NORMAL: "通过",
  // WARNING: "预警",
  // TIMEOUT: "超时",
  // END: "终止",
  // PAUSE: "暂停",
  // RECALL: "撤销",
  // ERROR: "错误",
  // REJECT: "驳回",
  TRANSFER: "转办",
};

@connect(({FlowHandle, loading}) => ({
  flowHandleStore: FlowHandle,
  loading,
}))
class ProcessRecord extends Component {
  state = {
    visible: false,
    activityId: "",
    taskId: null,
    secondVisible: null,
    visibleTask: null,
    formDetailVisible: false,
    taskFormUrl: "",
    // processFormUrl: "",
    fieldData: undefined,
    fileViewVisible: false,
    attachInfoList: [],
  };

  constructor(props) {
    super(props);
    this.renderItem = this.renderItemWithCurrentId.bind(
      this,
      this.onDetail,
      this.toggleSecond,
    );
  }

  // renderHandle = (onDetail, item, operator) => {
  renderHandle = (onDetail, item) => {
    const {handleTaskVisible, customFormVisible, actype} = this.props;

    const {nodeAuth} = item;
    let showMore = false;

    if (nodeAuth) {
      showMore =
        nodeAuth.addSignature ||
        nodeAuth.delay ||
        // nodeAuth.signIn ||
        nodeAuth.reject ||
        nodeAuth.transfer;
    }

    const Detail = (
      <span className={styles.detail} onClick={() => onDetail(item)}>
        详情
      </span>
    );

    const SIGNIN = (
      <>
        <span className={styles.detail} onClick={() => onDetail(item)}>
          详情
        </span>
        <span
          className={styles.detail}
          onClick={() => {
            handleTaskVisible("signVisible", true, item.taskId);
          }}
        >
          签收
        </span>
      </>
    );

    const menu = showMore ? (
      <Menu>
        {nodeAuth.addSignature && (
          <Menu.Item>
            <span
              onClick={() => {
                handleTaskVisible("addSignVisible", true, item.taskId);
              }}
            >
              加签
            </span>
          </Menu.Item>
        )}
        {nodeAuth.transfer && (
          <Menu.Item>
            <span
              onClick={() => {
                handleTaskVisible("transferVisible", true, item.taskId);
              }}
            >
              转办
            </span>
          </Menu.Item>
        )}
        {nodeAuth.delay && (
          <Menu.Item>
            <span
              onClick={() => {
                handleTaskVisible("delayVisible", true, item.taskId);
              }}
            >
              延期
            </span>
          </Menu.Item>
        )}
        {nodeAuth.reject && (
          <Menu.Item>
            <span
              onClick={() => {
                handleTaskVisible("rejectVisible", true, item.taskId);
              }}
            >
              驳回
            </span>
          </Menu.Item>
        )}
      </Menu>
    ) : null;

    const HandleAndMORE = (
      <>
        <span
          className={styles.detail}
          onClick={() => {
            if (isPhone()) {
              router.push(`/embedded/phone/todo-detail/form?taskId=${item.taskId}&editable=1`);
            } else {
              customFormVisible(true, item);
            }
          }}
        >
          处理
        </span>
        {showMore && (
          <Dropdown overlay={menu} placement="bottomRight">
            <span className={styles.detail}>更多</span>
          </Dropdown>
        )}
      </>
    );

    if (actype === "todo") {
      // if (item.taskStatus === "TODO" && !operator) {
      if (item.taskStatus === "TODO" && nodeAuth.signIn) {
        return SIGNIN;
      } else if (
        item.nodeAuthShow &&
        item.taskStatus === "TODO" &&
        !item.multiInstance
      ) {
        return HandleAndMORE;
      } else if (item.taskId && !item.multiInstance) {
        return Detail;
      }
    } else if (actype !== "todo") {
      if (item.taskId && !item.multiInstance) {
        return Detail;
      }
    }
  };

  renderItemWithCurrentId = (onDetail, toggleSecond, item, index) => {
    // const statusClassName = item.status === "NORMAL" ? "" : styles.error;
    // const resultClassName = styles[item.approval === "通过" ? "ok" : "error"];
    const {secondVisible, visibleTask} = this.state;
    const {handleTaskVisible, actype, customFormVisible, result = {}} = this.props;

    const isDealFinish =
      Number(item.numOfHandler) - Number(item.numOfCompleted);
    const toggleTask = (taskId) => {
      this.setState({
        visibleTask: visibleTask === taskId ? null : taskId,
      });
    }

    // 需求是：审批进度中，已处理的任务，人名旁边增加工号显示 员工工号 employeeCode
    let employeeCode = (item?.taskStatus === 'DONE' || item?.taskNodeType !== 'node') && item?.employeeCode ? `[${item.employeeCode}]` : '';
    let operator = item?.operatorName?.split(",").map((v, i) => <div key={i}>{`${v} ${employeeCode}`}</div>) ?? '';
    if (Array.isArray(item.operatorNameList) && item.operatorNameList.length > 0) {
      // eslint-disable-next-line array-callback-return
      operator = item.children.map((v, i) => {
        employeeCode = (v?.taskStatus === 'DONE' || v?.taskNodeType !== 'node') && v?.employeeCode  ? `[${v.employeeCode}]` : '';
        if (item.taskId !== visibleTask) {
          if (i < 2) {
            return (
              <div key={i}>
                <div style={{display: 'flex'}}>
                  <span style={{minWidth: '160px'}}>{`${v.operatorName} ${employeeCode}`}</span>
                  <span style={{minWidth: "180px"}}>{v.taskNodeTime}</span>
                  <span style={{minWidth: "160px"}}>{v.taskStatus === "DONE" ? "已处理" : "待处理"} {v.readFlag===1?"(已读)":"(未读)"}</span>
                  <span style={{minWidth: "50px"}}>{Status[v.approvalStatus]}</span>
                  <span style={{minWidth: "690px"}}>
                    {v.comment && `意见：${v.comment}`}
                  </span>
                </div>
                <div>
                  {i === 1 && item.children.length > 2 ?
                    <Icon style={{color: '#2766ff'}} type="down" onClick={() => toggleTask(item.taskId)} /> : ''}
                </div>
              </div>
            )
          }
        } else {
          return (
            <div style={{paddingRight: 15}} key={i}>
              <div style={{display: 'flex'}}>
                <span style={{minWidth: '160px'}}>{`${v.operatorName} ${employeeCode}`}</span>
                <span style={{minWidth: "180px"}}>{v.taskNodeTime}</span>
                <span style={{minWidth: "160px"}}>{v.taskStatus === "DONE" ? "已处理" : "待处理" } {v.readFlag===1?"(已读)":"(未读)"}</span>
                <span style={{minWidth: "50px"}}>{Status[v.approvalStatus]}</span>
                <span style={{minWidth: "690px"}}>
                  {v.comment && `意见：${v.comment}`}
                </span>
              </div>
              <div>
                {i === 1 ? <Icon style={{color: '#2766ff'}} type="up" onClick={() => toggleTask(item.taskId)} /> : ''}
              </div>
            </div>
          )
        }
      })
    }

    return (
      <Step
        title={
          <div>
            <div className={styles.desc}>
              <span style={{minWidth: item.operatorNameList?.length > 0 ? "1130px" : "160px", color: '#000000A6'}}>
                {operator || ``}
              </span>
              <span style={{minWidth: "180px", color: '#000000A6'}}>
                {item.operatorNameList?.length > 0 ? "" : (item.taskNodeTime || "--")}
              </span>
              <span style={{minWidth: "100px"}}>
                {!item.multiInstance && (item.taskNodeType === 'start' || item.taskStatus === 'DONE') && (
                  <span
                    style={{color: '#608eff', cursor: 'pointer', minWidth: "100px"}}
                    onClick={() => this.onFormDetail(item)}
                  >
                    {item.taskNodeType === 'start' ? '' : '表单详情'}
                  </span>
                )}
              </span>
              {!item.multiInstance && (item.taskStatus === "DONE" || (item.taskStatus === "TODO" && !(result?.taskStatus !== "TODO" && result?.status !== "NORMAL"))) ? (
                <span style={{color: '#608eff', cursor: 'pointer'}} onClick={() => this.onFileView(item)}>
                  {item.taskNodeType === 'start' ? '' : '附件列表'}
                </span>
              ) : null}
              {/* {this.renderHandle(onDetail, item, operator)} */}

              {/* {item.multiInstance && (
                <span
                  className={styles.detail}
                  onClick={() => toggleSecond(item.taskId)}
                >
                  {item.taskId === secondVisible ? "收起" : "展开"}
                </span>
              )} */}
            </div>

            {item.multiInstance && (
              <div
                className={styles.processRecord}
              >
                <div className={styles.processRecordTitle}>
                  <span style={{minWidth: "160px"}}>
                    <span>任务派发：</span>
                    <span>{`${item.numOfInstances}人`}</span>
                  </span>
                  <span style={{minWidth: "240px"}}>
                    <span>需处理人数：</span>
                    <span>{`${item.numOfHandler}人`}</span>
                  </span>
                </div>
              </div>
            )}

            <div className={styles.desc}>
              <span style={{
                minWidth: "160px",
                color: (item.taskNodeType === "start" || (item.taskStatus === "DONE" && item.status !== "REJECT")) ? '#52c41a' : (item.status === "NORMAL" ? '#1576fb' : '#ff4d4f'),
              }}
              >
                <span>{item.taskName}</span>
                {item.multiInstance && <span>(会签)</span>}
              </span>

              {item.taskNodeType === "start" ? (
                <>
                  <span>
                      {item.comment && `提交意见：${item.comment}`}
                    </span>
                </>
              ) : null}

              {item.taskNodeType === "node" ? (
                <>
                  <span style={{minWidth: "180px"}}>
                    {!item.multiInstance && (
                      <span className={styles.mr16}>
                        {item.taskStatus === "DONE" ? "已处理" : "待处理"}
                      </span>
                    )}
                    {item.multiInstance && (
                      <span className={styles.mr16}>
                        {item.taskStatus === "DONE" ? "已完结" : "待完结"}
                      </span>
                    )}
                    {item.taskStatus === "DONE" && (
                      <span className={styles.handleResult}>
                        {Status[item.approvalStatus]}
                      </span>
                    )}
                  </span>
                  <span style={{minWidth: "100px"}}>
                    {item.multiInstance && item.taskStatus === 'DONE' && (
                      <span style={{color: '#608eff', cursor: 'pointer'}} onClick={() => this.onFormDetail(item)}>
                        {item.taskNodeType === 'start' ? '' : '表单详情'}
                      </span>
                    )}
                  </span>
                  {item.multiInstance && (item.taskStatus === "DONE" || (item.taskStatus === "TODO" && !(result?.taskStatus !== "TODO" && result?.status !== "NORMAL")) || item?.children?.some(ele => ele?.taskStatus === "DONE")) && (
                    <span style={{color: '#608eff', cursor: 'pointer'}} onClick={() => this.onFileView(item)}>
                      {item.taskNodeType === 'start' ? '' : '附件列表'}
                    </span>
                  )}
                  {!item.multiInstance && (
                    <span>
                      {item.comment && `意见：${item.comment}`}
                    </span>
                  )}
                  {/* {item.taskName === "审批节点" ||
                  (item.multiInstance && item.approval) ? (
                    <span>
                      <span className={styles.mr16}>审批结果：</span>
                      <span className={resultClassName}>{item.approval}</span>
                    </span>
                  ) : null} */}
                </>
              ) : null}
            </div>
            {item.multiInstance && (
              <div
                className={styles.processRecord}
                style={{
                  display: item.taskId === secondVisible ? "block" : "none",
                }}
              >
                <div className={styles.processRecordTitle}>
                  <span style={{minWidth: "190px"}}>
                    <span>任务派发：</span>
                    <span>{`${item.numOfInstances}人`}</span>
                  </span>
                  <span style={{minWidth: "240px"}}>
                    <span>需处理：</span>
                    <span>{`${item.numOfHandler}人`}</span>
                  </span>
                  <span style={{minWidth: "200px"}}>
                    <span>已处理：</span>
                    <span>{`${item.numOfCompleted}人`}</span>
                  </span>
                </div>
                <div style={{padding: "0 8px"}}>
                  <SecondProcessRecord
                    data={item.children}
                    isDealFinish={isDealFinish}
                    handleTaskVisible={handleTaskVisible}
                    customFormVisible={customFormVisible}
                    actype={actype}
                    nodeAuth={item.nodeAuth}
                    // renderHandle={this.renderHandle}
                  />
                </div>
              </div>
            )}
          </div>
        }
        status={item.taskStatus === "TODO" ? "process" : (item.taskNodeType === "start" || item.status === "NORMAL" ? "finish" : "error")}
        // title={item.taskNodeTime}
        key={index}
      />
    );
  };

  onDetail = ({activityId, taskId}) => {
    if (isPhone()) {
      router.push(`/embedded/phone/todo-detail/form?taskId=${taskId}`);
    } else {
      this.setState({
        activityId,
        visible: true,
        taskId,
      });
    }
  }

  onFormDetail = (item) => {
    const {dispatch} = this.props;
    this.setState({
      formDetailVisible: true,
      taskId: item.taskId,
    }, () => {
      dispatch({
        type: "FlowHandle/isExternalForm",
        payload: {taskId: item.taskId},
      }).then(({errCode, datas}) => {
        if (errCode === 0 && datas === true) {
          dispatch({
            type: "FlowHandle/historyExternalTaskForm",
            payload: {taskId: item.taskId},
          }).then(({errCode: errCode1, datas: datas1}) => {
            const {taskFormUrl = ''} = datas1;
            if (errCode1 === 0) {
              this.setState({
                taskFormUrl,
              })
            }
          })
        } else {
          dispatch({
            type: "FlowHandle/getFormLog",
            payload: {taskId: item.taskId},
          }).then(({datas: datas2}) => {
            const {fieldData} = datas2 || {};
            this.setState({fieldData});
          });
        }
      })
    })
  }

  onFileView = (item) => {
    const {dispatch, processInstanceId} = this.props;
    this.setState({
      fileViewVisible: true,
      taskId: item.taskId,
    }, () => {
      dispatch({
        type: "FlowHandle/getAttachInfoList",
        payload: {taskId: item.taskId, processInstanceId, serviceType: 1},
      }).then(({errCode, datas}) => {
        if (errCode === 0) {
          this.setState({attachInfoList: datas})
        }
      })
    })
  }

  toggleSecond = (taskId) => {
    const {secondVisible} = this.state;
    this.setState({
      secondVisible: secondVisible === taskId ? null : taskId,
    });
  };

  render() {
    const {
      visible,
      activityId,
      taskId,
      formDetailVisible,
      taskFormUrl,
      fieldData,
      fileViewVisible,
      attachInfoList,
    } = this.state;
    const {flowRecords = [], data = {}, loading} = this.props;
    const fileViewLoading = loading.effects["FlowHandle/getAttachInfoList"] || false;
    const {processInstanceId} = data;
    let currentStep = 0;
    let type;
    // let typeNodeIndex = 0;
    if (flowRecords.length) {
      for (const [i, record] of flowRecords.entries()) {
        type = record.taskNodeType;
        if (type === "start" || type === "end") {
          currentStep += 1;
          /* } else if (type === "end") {
            currentStep += 2;
            break; */
        } else if (record?.taskStatus === "DONE") {
          // typeNodeIndex += 1;
          currentStep += 1;
        } else if (record?.taskStatus === "TODO") {
          /*
          typeNodeIndex += 1;
          // 第1和2个非开始及结束类型， 状态为TODO,通知业务系统填充数据
          if (typeNodeIndex === 1) {
            record.noticeBusinessSystem = true;
            const next = flowRecords[i+1];
            if (next) {
              next.noticeBusinessSystem = true;
            }
          }
          */
          currentStep = i;
          break;
        }
      }
    }
    return (
      <Row className={styles.root}>
        <Steps direction="vertical" size="small" current={currentStep}>
          {/* mockData.map(this.renderItem) */}
          {flowRecords.length && flowRecords.map(this.renderItem)}
        </Steps>
        {visible && (
          <RecordDetail
            activityId={activityId}
            taskId={taskId}
            onCancel={() => this.setState({visible: false})}
            processInstanceId={processInstanceId}
            visible={visible}
          />
        )}
        {formDetailVisible && (
          <FormDetail
            taskId={taskId}
            taskFormUrl={taskFormUrl}
            onCancel={() => this.setState({formDetailVisible: false})}
            visible={formDetailVisible}
            fieldData={fieldData}
          />
        )}
        {fileViewVisible && (
          <Modal
            title="附件列表"
            visible={fileViewVisible}
            onCancel={() => this.setState({fileViewVisible: false})}
            width="800px"
            centered
            destroyOnClose
            hideRequiredMark
            labelAlign="left"
            footer={[
              <Button key="back" onClick={() => this.setState({fileViewVisible: false})}>
                关闭
              </Button>,
            ]}
          >
            <Spin spinning={fileViewLoading} delay={300}>
              {(attachInfoList || []).map(file => {
                return (
                  <FileView
                    key={file.id}
                    fileMessage={file}
                    serviceType='1'
                  />
                );
              })}
              {JSON.stringify(attachInfoList) === "[]" && !fileViewLoading && (
                <div className={styles.no_data}>
                  <span>暂无附件列表</span>
                </div>
              )}
            </Spin>
          </Modal>
        )}
      </Row>
    );
  }
}

export default ProcessRecord;
